package main

import (
	"com.mgface/container"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/urfave/cli"
	"os"
)

const usage = `mydocker is a simple application.
					The purpose of this project is to learn how docker works and
					how dto write a docker by ourselves enjoy it,just for run.`

var runCommand = cli.Command{
	Name: "run",
	Usage: `create a container with namespace and cgroups limit
			my docker run -ti [command]`,
	Flags: []cli.Flag{
		cli.BoolFlag{
			Name:  "ti",
			Usage: "enable tty",
		},
	},
	Action: func(context *cli.Context) error {
		if len(context.Args()) < 1 {
			return fmt.Errorf("miss container command")
		}
		cmd := context.Args().Get(0)
		log.Infof("--->cmd参数:%s", cmd)
		tty := context.Bool("ti")
		Run(cmd, tty)
		return nil
	},
}

func Run(cmd string, tty bool) {
	parent := container.NewParentProcess(tty, cmd)
	if err := parent.Start(); err != nil {
		log.Error(err)
	}
	parent.Wait()
	os.Exit(-1)
}

var initCommand = cli.Command{
	Name:  "init",
	Usage: `Init container process run users's process in container.Do not call it outside'`,
	Action: func(ctx *cli.Context) error {
		log.Infof("init come on")
		cmd := ctx.Args().Get(0)
		log.Infof("command %s", cmd)
		err := container.RunContainerInitProcess(cmd, nil)
		return err
	},
}

func main() {
	app := cli.NewApp()
	app.Name = "mydocker"
	app.Usage = usage
	app.Commands = []cli.Command{
		runCommand,
		initCommand,
	}
	app.Before = func(context *cli.Context) error {
		log.SetFormatter(&log.JSONFormatter{})
		log.SetOutput(os.Stdout)
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
